package com.zkingsoft.common.service.impl;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.matrix.core.constance.MatrixConstance;
import com.matrix.core.constance.SystemErrorCode;
import com.matrix.core.exception.GlobleException;
import com.matrix.core.pojo.PaginationVO;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.ModelUtils;
import com.matrix.core.tools.UUIDUtil;
import com.matrix.core.tools.WebUtil;
import com.zkingsoft.common.bean.SysUserLoginRecord;
import com.zkingsoft.common.bean.SysUsers;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.common.constance.AppMessageCode;
import com.zkingsoft.common.dao.SysUsersDao;
import com.zkingsoft.common.service.SysUsersService;
import com.zkingsoft.common.tools.PasswordUtil;
import com.zkingsoft.common.tools.ServiceUtil;

/**
 * 用户管理service
 * 
 * @author JIANGYOUYAO
 * @email 935090232@qq.com
 * @date 2017年12月5日
 */
@Service
public class SysUsersServiceImpl implements SysUsersService {

	private static final String SU_ID = "su_id";

	private static final String SU_ACCOUNT = "su_account";

	@Autowired
	private SysUsersDao sysUsersDao;

	@Autowired
	private ServiceUtil serviceUtil;

	private final String tableName = "sys_users";

	@Override
	public int addCompanySuper(SysUsers admin) {
		admin.setSuUserType(AppConstance.USER_TYPE_ADMIN);
		return add(admin);
	}

	@Override
	public int addAdmin(SysUsers sysUsers) {
		sysUsers.setSuUserType(AppConstance.USER_TYPE_EMPLOYEE);
		return add(sysUsers);
	}

	@Override
	public int add(SysUsers sysUsers) {

		// 判断账号是否重复
		if (serviceUtil.addCheckRepeat(tableName, SU_ACCOUNT, sysUsers.getSuAccount())) {
			throw new GlobleException(AppMessageCode.User.ACCOUNT_EXIST, sysUsers.getSuAccount());
		}

		// 设置一些基本信息
		SysUsers loginUser = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
		sysUsers.setCreateBy(loginUser.getSuName());
		sysUsers.setUpdateBy(loginUser.getSuName());
		sysUsers.setSuId(UUIDUtil.getRandomID());
		sysUsers.setSuAccountStatus(AppConstance.ACCOUNT_STATUS_ACTIVATE);
		sysUsers.setSuValid(AppConstance.RECORD_VALID);
		sysUsers.setCompanyId(loginUser.getCompanyId());

		try {
			sysUsers.setSuRegisterTime(new Date());
			sysUsers.setSuPassword(PasswordUtil.getEncrypUserPwd(sysUsers));
		} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
			LogUtil.error("用户密码加密失败", e);
			throw new GlobleException(SystemErrorCode.DATA_ADD_FAIL, sysUsers.getSuAccount());
		}
		return sysUsersDao.insert(sysUsers);
	}

	@Override
	public int modifyByMap(SysUsers oldSysUsers, SysUsers newSysUsers) {
		// 判断账号是否重复
		if (serviceUtil.updateCheckRepeat(tableName, SU_ACCOUNT, newSysUsers.getSuAccount(), SU_ID,
				newSysUsers.getSuId())) {
			throw new GlobleException(AppMessageCode.User.ACCOUNT_EXIST, newSysUsers.getSuAccount());
		}
		SysUsers loginUser = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
		newSysUsers.setUpdateBy(loginUser.getSuName());
		Map<String, Object> modifyMap = null;
		try {
			if (!ModelUtils.isModified(oldSysUsers, newSysUsers)) {
				return MatrixConstance.DML_SUCCESSS;
			}
			modifyMap = ModelUtils.comparePojo2Map(oldSysUsers, newSysUsers);
		} catch (Exception e) {
			throw new GlobleException(SystemErrorCode.DATA_UPDATE_FAIL, e, newSysUsers.getSuAccount());
		}
		if (modifyMap.size() > 0) {
			modifyMap.put("suId", oldSysUsers.getSuId());
			return sysUsersDao.updateByMap(modifyMap);
		}
		return MatrixConstance.DML_SUCCESSS;
	}

	@Override
	public int modifyByModel(SysUsers sysUsers) {

		return sysUsersDao.updateByModel(sysUsers);

	}

	@Override
	public int remove(List<String> list) {

		return sysUsersDao.deleteByIds(list);

	}

	@Override
	public int removeById(String suId) {

		return sysUsersDao.deleteById(suId);

	}

	@Override
	public int removeByModel(SysUsers sysUsers) {

		return sysUsersDao.deleteByModel(sysUsers);

	}

	@Override
	public List<SysUsers> findInPage(SysUsers sysUsers, PaginationVO pageVo) {

		return sysUsersDao.selectInPage(sysUsers, pageVo);

	}

	@Override
	public List<SysUsers> findByModel(SysUsers sysUsers) {

		return sysUsersDao.selectByModel(sysUsers);

	}

	@Override
	public int findTotal(SysUsers sysUsers) {

		return sysUsersDao.selectTotalRecord(sysUsers);

	}

	@Override
	public SysUsers findById(String suId) {

		return sysUsersDao.selectById(suId);

	}

	@Override
	public void lockUser(String suAccount) {
		sysUsersDao.changeUserStatus(suAccount, AppConstance.ACCOUNT_STATUS_LOCKED);
	}

	@Override
	public void unlockUser(String suAccount) {
		// 修改登录错误的日志
		cleanUserTodayErrorLoginTime(suAccount);

		sysUsersDao.changeUserStatus(suAccount, AppConstance.ACCOUNT_STATUS_ACTIVATE);
	}

	@Override
	public int countUserTodayErrorLoginTimes(String suAccount) {
		return sysUsersDao.countUserTodayErrorLoginTimes(suAccount);
	}

	@Override
	public void addUserLoginRecord(SysUserLoginRecord loginRecord) {
		sysUsersDao.insertLoginRecord(loginRecord);
	}

	@Override
	public void cleanUserTodayErrorLoginTime(String suAccount) {
		sysUsersDao.cleanUserTodayErrorLoginTime(suAccount);

	}

}